package com.gyul.findmystock.services;

import java.util.Calendar;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;

import com.gyul.findmystock.util.Constants;
import com.gyul.findmystock.util.PreferencesUtils;


public class FindMyStockService extends Service {
	static final String TAG = "FindMyStockService";
			
	Context mContext;
	WakeLock lock = null;
	static FindMyStockService self = null;
	
	PendingIntent mRepeatIntent = null;
	
	static public FindMyStockService getService() {
		return self;
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		super.onStartCommand(intent, flags, startId);
		
		mContext = this.getApplicationContext();
		
		PowerManager powerManager = (PowerManager)this.getSystemService(Context.POWER_SERVICE);
		lock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
		lock.acquire();		
		
		IntentFilter filter = new IntentFilter(Constants.ACTION_FINDMYSTOCK_REPEAT);
		filter.addAction(Constants.ACTION_STOP_GA_ANALYSIS);
		
		registerReceiver(analysisReceiver, filter);
		
		setRepeatingAlarm();
		
		self = this;
		
		return START_STICKY;
	}
		
	@Override
	public void onDestroy() {
		Log.i(TAG, "onDestroy()");
		
		AlarmManager alarmManager = (AlarmManager)mContext.getSystemService(ALARM_SERVICE);
		alarmManager.cancel(mRepeatIntent);		
		
		if ( lock != null && lock.isHeld() ) {			
			lock.release();
			lock = null;
		}
		
		unregisterReceiver(analysisReceiver);
				
		self = null;
		
		super.onDestroy();
	}
	
	public void setRepeatingAlarm() {
		Log.i(TAG, "setRepeatingAlarm");
		Intent updateIntent = new Intent(Constants.ACTION_FINDMYSTOCK_REPEAT);
		mRepeatIntent = PendingIntent.getBroadcast(mContext, 0, updateIntent, PendingIntent.FLAG_CANCEL_CURRENT);		
		AlarmManager alarmManager = (AlarmManager)mContext.getSystemService(ALARM_SERVICE);
		alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), Constants.MINUTE_15_INTERVAL, mRepeatIntent);
	}		
	
	BroadcastReceiver analysisReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			PreferencesUtils.initialize();
			
			String action = intent.getAction();
			
			if ( action.equals(Constants.ACTION_FINDMYSTOCK_REPEAT)) {
				Calendar cal = Calendar.getInstance();
				int week = cal.get(Calendar.DAY_OF_WEEK);
				int hour = cal.get(Calendar.HOUR_OF_DAY);
					
				if ( week == Calendar.SATURDAY || week == Calendar.SUNDAY ) {
					startUpdateGA();
				} else if (  0 <= hour && hour <= 14 ) {
					startUpdateGA();
				} else if ( 17 <= hour && hour <= 23 ) {
					startUpdateGA();
				} else if ( hour == 15 ) {
					PreferencesUtils.setBoolean(Constants.QUOTE_STATE, Constants.NEED_QUOTE_UPDATE);
				} else if ( 16 == hour ) {
					boolean quoteState = PreferencesUtils.getBoolean(Constants.QUOTE_STATE);
					
					if ( quoteState == Constants.NEED_QUOTE_UPDATE ) {
						startUpdateQuote();
					}
						
					PreferencesUtils.setBoolean(Constants.QUOTE_STATE, Constants.QUOTE_UPDATED);
				}			
			} else if ( action.equals(Constants.ACTION_STOP_GA_ANALYSIS)) {
				stopUpdateGA();
			}
		}
	};
	
	public void startUpdateGA() {
		if ( PreferencesUtils.getBoolean(Constants.UPDATE_ANALYSIS_SERVICE_ENABLED) == true ) {
			Intent updateGAIntent = new Intent(mContext, UpdateAnalysisService.class);
			mContext.startService(updateGAIntent);
		}
	}
	
	public void stopUpdateGA() {
		Intent updateGAIntent = new Intent(mContext, UpdateAnalysisService.class);
		mContext.stopService(updateGAIntent);
	}
	
	public void startUpdateQuote() {
		if ( PreferencesUtils.getBoolean(Constants.UPDATE_QUOTE_SERVICE_ENABLED) == true ) {
			Intent updateQuoteIntent = new Intent(mContext, UpdateQuoteService.class);
			mContext.startService(updateQuoteIntent);
		}
	}
	

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
}
